import React from 'react'
import './comment.css'

class Comment extends React.Component {
  state = {
    list: [
      {
        id: 1,
        name: 'jack',
        text: '沙发~'
      },
      {
        id: 2,
        name: 'rose',
        text: '沙发2号~'
      }
    ],
    userName: '',
    txt: ''
  }
  handleChange = e => {
    console.log(e)
    const { name, value } = e.target
    this.setState({
      [name]: value
    })
  }
  ifList = () => {
    if (this.state.list.length >= 1) {
      return (
        <ul>
          {this.state.list.map(item => (
            <li key={item.id}>
              <div style={{ fontSize: '22px' }}>评论人:{item.name}</div>
              <div style={{ fontSize: '12px', margin: '10PX 0PX' }}>
                评论内容：{item.text}
              </div>
            </li>
          ))}
        </ul>
      )
    } else {
      return <div className='i3'>暂无评论，快去评论吧~</div>
    }
  }
  handleClick = () => {
    const { list, userName, txt } = this.state
    console.log(userName, txt)
    // list.push({
    //   id: Math.random(), // id唯一的给随机数
    //   name: this.state.userName,
    //   text: this.state.txt
    // })
    // 非空校验
    if (userName.trim() === '' || txt.trim() === '') {
        alert('评论人和内容不得为空')
        return
    } {
        const newList = [{
            id: Math.random(), // id唯一的给随机数
         name: this.state.userName,
         text: this.state.txt
        }, ...list]
        // 更新list
        this.setState({
          list: newList,
          userName: '',
          txt: ''
        })
    }
    
  }
  render () {
    const { userName, txt } = this.state
    return (
      <div className='b1'>
        <input
          type='text'
          className='i1'
          placeholder='请输入评论人'
          value={userName}
          name='userName'
          onChange={this.handleChange}
        ></input>
        <textarea
          rows='7'
          cols='51'
          className='i2'
          placeholder='请输入评论内容'
          value={txt}
          name='txt'
          onChange={this.handleChange}
        ></textarea>
        <button onClick={this.handleClick}>发表评论</button>
        <div>{this.ifList()}</div>
      </div>
    )
  }
}
export default Comment
